package com.study.security.core.social.weixin.api.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.study.security.core.social.weixin.api.WeiXin;
import com.study.security.core.social.weixin.api.WeiXinUserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author liyongkui
 */
public class WeiXinImpl extends AbstractOAuth2ApiBinding implements WeiXin {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 获取微信用户信息服务
     */
    private static final String URL_GET_USERINFO="https://api.weixin.qq.com/sns/userinfo?openid=%s";

    public WeiXinImpl(String accessToken) {
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
    }

    /**
     * 默认的StringHttpMessageConverter charset为iso8859-1 修改为utf8
     * @return
     */
    @Override
    protected List<HttpMessageConverter<?>> getMessageConverters() {
        List<HttpMessageConverter<?>> messageConverters = super.getMessageConverters();
        messageConverters.remove(0);
        messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return messageConverters;
    }

    @Override
    public WeiXinUserInfo getUserInfo(String openId) {
        String url = String.format(URL_GET_USERINFO, openId);
        String response = getRestTemplate().getForObject(url, String.class);
        logger.info("微信获取用户信息返回：{}",response);
        WeiXinUserInfo weiXinUserInfo = null;
        try {
             weiXinUserInfo = objectMapper.readValue(response, WeiXinUserInfo.class);
        } catch (JsonProcessingException e) {
            logger.info("微信获取用户信息失败");
        }
        return weiXinUserInfo;
    }


}
